"""星座时-空分析系统使用示例"""

import numpy as np
from astropy import units as u
from astropy.time import Time, TimeDelta
from poliastro.bodies import Earth
from poliastro.twobody import Orbit
from poliastro.twobody.sampling import EpochsArray
from poliastro.frames import Planes
import time

from satellite import Satellite, SatelliteConstellation, Sensor, SensorType
from target import GroundTarget, GroundTargetGroup
from access import AccessCalculator
from propagator import PropagationMethod
from visualization import ConstellationVisualizer


def create_leo_satellites(plane = Planes.EARTH_EQUATOR, num_satellites=6, altitude=500*u.km, inclination=60*u.deg, 
                         epoch=Time.now(), raan_offset=60*u.deg):
    """
    创建LEO卫星星座
    
    参数:
        num_satellites: 卫星数量
        altitude: 轨道高度
        inclination: 轨道倾角
        epoch: 历元
        raan_offset: 升交点赤经偏移量
        
    返回:
        卫星星座对象
    """
    # 创建星座
    constellation = SatelliteConstellation("LEO星座")
    
    # 创建卫星
    for i in range(num_satellites):
        # 计算升交点赤经
        raan = i * raan_offset
        
        # 创建轨道
        orbit = Orbit.circular(
            Earth,
            altitude,
            inclination,
            raan,
            epoch = epoch,
            plane = plane
        )
        
        # 创建卫星
        satellite = Satellite(f"LEO-{i+1}", orbit)
        
        # 添加传感器
        optical_sensor = Sensor("光学相机", SensorType.OPTICAL, 0, 60)
        satellite.add_sensor(optical_sensor)
        
        # 设置传播方法
        satellite.set_propagation_method(PropagationMethod.J2)
        
        # 添加到星座
        constellation.add_satellite(satellite)
        
    return constellation

TARGET_LOCATIONS = [("北京", 39.8825, 123.912), ("上海", 31.2, 121.5), ("广州", 23.1, 113.3)]
def create_targets(locations=[("北京", 39.8825, 123.912), ("上海", 31.2, 121.5), ("广州", 23.1, 113.3)]):
    """
    创建地面目标
    
    参数:
        locations: 目标位置列表，每个元素为(名称, 纬度, 经度)元组
        
    返回:
        目标组对象
    """
    # 创建目标组
    target_group = GroundTargetGroup("中国城市")
    
    # 创建目标
    for name, lat, lon in locations:
        target = GroundTarget(name, lat, lon)
        target_group.add_target(target)
        
    return target_group

def demo_optimized_workflow():
    """展示优化后的工作流程"""
    
    time_stamp = time.time()
    # 设置20 Mar 2025 04:00:00.000 UTC
    epoch_time = Time('2025-03-20 04:00:00.000', format='iso', scale='utc')
    # 创建星座和目标
    constellation = create_leo_satellites(plane=Planes.EARTH_EQUATOR, num_satellites=6, epoch=epoch_time)
    targets = create_targets(TARGET_LOCATIONS)
    
    # 设置分析时间窗口
    start_time = epoch_time
    end_time = start_time + TimeDelta(.2 * u.day)
    
    print(f"分析从 {start_time.iso} 到 {end_time.iso} 的访问窗口...")
    
    # 计算访问窗口（包含轨迹点）
    access_results = AccessCalculator.calculate_constellation_access_multiprocessing(
        constellation,
        targets, 
        start_time,
        end_time,
        step=30 * u.s
    )
    # 打印访问窗口结果
    print("\n访问窗口分析结果:")
    for satellite, target_results in access_results:
        print(f"\n卫星: {satellite.name}")
        
        for target, windows in target_results:
            print(f"  目标: {target.name}")
            
            if not windows:
                print("    无访问窗口")
            else:
                total_access_time = sum((w.end_time - w.start_time).to(u.min).value for w in windows)
                print(f"    总访问时间: {total_access_time:.2f} 分钟")
                print(f"    访问窗口次数: {len(windows)}")
                
                for i, window in enumerate(windows[:3]):  # 只显示前三个窗口
                    duration = (window.end_time - window.start_time).to(u.min).value
                    print(f"    窗口 {i+1}: {window.start_time.iso} 至 {window.end_time.iso} (持续时间: {duration:.2f} 分钟)")
                
                if len(windows) > 3:
                    print(f"    ... 还有 {len(windows) - 3} 个窗口")
    print(f"calculator access: {(time.time() - time_stamp):.2f} 秒")
    time_stamp = time.time()
    # 直接使用预计算的轨迹点进行可视化
    visualizer = ConstellationVisualizer()
    fig = visualizer.plot_constellation_groundtracks(
        targets,
        access_results=access_results  # 传递预计算的访问结果
    )
    
    try:
        fig.show()
        print("可视化结果已显示。")
    except:
        print("无法显示图形，请确保在支持图形显示的环境中运行。")
    print(f"plot access windows time: {(time.time() - time_stamp):.2f} 秒")
    return fig


if __name__ == "__main__":
    # main()
    # 取消下面的注释以运行优化工作流程演示
    demo_optimized_workflow() 

